package marchenko.springdao.repository.book_class;

import java.util.List;

import marchenko.springdao.domain.BookClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class BookClassRepositoryImpl implements BookClassRepository {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	private final static String SELECT_ALL = "select bc.id, bc.name, a.id as author_id, a.name as author_name, "
			+ "g.id as genre_id, g.name as genre_name, bc.description "
			+ "from book_classes bc "
			+ "join authors a on a.id=bc.author_id "
			+ "join genres g on g.id=bc.genre_id ";
	
	public BookClass find(Integer id) throws DataAccessException {
		return jdbcTemplate.queryForObject(
				SELECT_ALL+" where id = ?",
				new BookClassMapper(), id);
	}

	public List<BookClass> findAll() throws DataAccessException {
		return jdbcTemplate.query(SELECT_ALL,
				new BookClassMapper());
	}

	public BookClass findByName(String name) throws DataAccessException {
		return jdbcTemplate.queryForObject(
				SELECT_ALL+"where bc.name = ?",
				new BookClassMapper(), name);
	}

	public boolean create(BookClass newinstance) throws DataAccessException {
		return jdbcTemplate
				.update("insert into book_classes (id, name, genre_id, author_id, description) values (?,?,?,?,?)",
						newinstance.getClassId(),
						newinstance.getClassName(), newinstance.getGenre()
								.getGenreId(), newinstance.getAuthor()
								.getAuthorId(), newinstance.getDescription()) > 0;
	}

	public boolean deleteById(Integer id) throws DataAccessException {
		return jdbcTemplate.update("delete from book_classes where id = ?", id) > 0;
	}
}
